package com.example.ruijiproject.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ruijiproject.domain.Category;
import com.example.ruijiproject.domain.Dish;
import com.example.ruijiproject.domain.DishDto;
import com.example.ruijiproject.domain.Result;
import com.example.ruijiproject.service.CategoryService;
import com.example.ruijiproject.service.DishFlavorService;
import com.example.ruijiproject.service.DishService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 添加菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody DishDto dishDto) {
        log.info("添加菜品: {}", dishDto);
        dishService.saveWithFlavor(dishDto);
        return Result.success("添加菜品成功！");
    }


    /**
     * 分页查询菜品
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize, String name) {
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        //这个就是我们到时候返回的结果
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo, queryWrapper);

        //对象拷贝，这里只需要拷贝一下查询到的条目数
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        //获取原records数据
        List<Dish> records = pageInfo.getRecords();

        //遍历每一条records数据
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //将数据赋给dishDto对象
            BeanUtils.copyProperties(item, dishDto);
            //然后获取一下dish对象的category_id属性
            Long categoryId = item.getCategoryId();  //分类id
            //根据这个属性，获取到Category对象（这里需要用@Autowired注入一个CategoryService对象）
            Category category = categoryService.getById(categoryId);
            //随后获取Category对象的name属性，也就是菜品分类名称
            String categoryName = category.getName();
            //最后将菜品分类名称赋给dishDto对象就好了
            dishDto.setCategoryName(categoryName);
            //结果返回一个dishDto对象
            return dishDto;
            //并将dishDto对象封装成一个集合，作为我们的最终结果
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        return Result.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDto> getById(@PathVariable Long id){
        log.info("查询菜品id:{}",id);
        DishDto dto = dishService.getWithFlavor(id);
        return Result.success(dto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody DishDto dishDto) {
        log.info("接收到的数据为：{}", dishDto);
        dishService.updateWithFlavor(dishDto);
        return Result.success("修改菜品成功");
    }

    /**
     * 删除菜品
     * @param ids 菜品id
     * @return
     */
    @DeleteMapping
    public Result<String> delete(Long ids){
        log.info("删除菜品id:{}",ids);
        dishService.removeById(ids);
        return Result.success("删除菜品成功");
    }

    /**
     * 更改售卖状态
     * @param status 0：启售 1：停售
     * @param ids 菜品id
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> updateStatus(@PathVariable Integer status,Long ids){
        log.info("修改菜品状态，id:{},status:{}",ids,status);
        //查询菜品
        Dish dish = dishService.getById(ids);
        dish.setStatus(status);
        dishService.updateById(dish);
        return Result.success("修改菜品状态成功");
    }

    @GetMapping("/list")
    public Result<List> getDishList(Long categoryId){
        log.info("查询菜品列表，categoryId:{}",categoryId);
        List<Dish> list = dishService.list(new LambdaQueryWrapper<Dish>().eq(categoryId != null, Dish::getCategoryId, categoryId));
        return Result.success(list);
    }
}
